package com.hjxy.codetools.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 网络请求基类
 */
public class NetUtil {
    /**
     * 网络post请求
     * @param postParam
     * @param postUrl
     * @return
     */
    public static String httpPost(String postParam, String postUrl) {

        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(postUrl).openConnection();
            //加入数据
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());
            buffOutStr.write(postParam.getBytes("UTF-8"));
            buffOutStr.flush();
            buffOutStr.close();

            //获取输入流
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 网络get请求
     * @param getUrl
     * @return
     */
    public static String httpGet(String getUrl) {

        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(getUrl).openConnection();
            //加入数据
            conn.setRequestMethod("GET");

            conn.setConnectTimeout(5 * 1000);

            //获取输入流
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
